﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sale.DTO;
using Sale.DTO.Merchandise;

namespace Sale.DataAccess.Repository
{
    public class RevenueRepository : BaseRepository
    {
        public void AddDailyRevenueItem(DailyRevenueDTO dto)
        {
            var entity = new DailyRevenue()
            {
                Id = dto.Id,
                QuantityInStock = dto.QuantityInStock,
                MerchandiseId = dto.Merchandise.Id,
                ImportQuantity = dto.ImportQuantity,
                AvgImportUnitPrice = dto.AvgImportUnitPrice,
                ExportUnitPrice = dto.ExportUnitPrice,
                ExportQuantity = dto.ExportQuantity,
                Date = dto.Date

            };

            Context.DailyRevenues.InsertOnSubmit(entity);
        }

        public bool CheckDailyRevenueItemExists(DateTime date, int merchandiseId, decimal? avgImportUnitPrice)
        {
            return Context.DailyRevenues.Any(
                e => e.Date.Date == date.Date
                && e.MerchandiseId == merchandiseId
                && e.AvgImportUnitPrice == avgImportUnitPrice);
        }

        public void UpdateDailyRevenueItem(DailyRevenueDTO dto)
        {
            var entity = GetEntity(dto.Id);


            entity.AvgImportUnitPrice = dto.AvgImportUnitPrice;
            entity.ImportQuantity = dto.ImportQuantity;


            entity.ExportQuantity = dto.ExportQuantity;
            entity.ExportUnitPrice = dto.ExportUnitPrice;

            entity.QuantityInStock = dto.QuantityInStock;
        }
        public DailyRevenueDTO GetDailyRevenueItem(DateTime date, int merchandiseId)
        {
            var entity = Context.DailyRevenues.SingleOrDefault(e => e.Date.Date == date.Date && e.MerchandiseId == merchandiseId);
            return ConvertToDTO(entity);
        }

        private DailyRevenueDTO ConvertToDTO(DailyRevenue entity)
        {
            var dto = new DailyRevenueDTO()
            {
                Id = entity.Id,
                QuantityInStock = entity.QuantityInStock,
                ImportQuantity = entity.ImportQuantity,
                AvgImportUnitPrice = entity.AvgImportUnitPrice,
                ExportUnitPrice = entity.ExportUnitPrice,
                ExportQuantity = entity.ExportQuantity,
                Date = entity.Date,
                Merchandise = ObjectMapper.MapSourceToDestination<Merchandise, MerchandiseDTO>(entity.Merchandise)

            };
            return dto;
        }
        private DailyRevenue GetEntity(Guid id)
        {
            var entity = Context.DailyRevenues.SingleOrDefault(e => e.Id == id);
            return entity;
        }
    }
}
